const {ccclass, property} = cc._decorator;

@ccclass
export class JoyStick extends cc.Component {

    @property(cc.Node)
    jsPoint:cc.Node;

    private _radius:number = 63.5;
    private _dir:cc.Vec2 = cc.v2(0, 0);

    public static Instance: JoyStick;

    public onLoad() {
        JoyStick.Instance = this;
        this.node.on("touchstart", this.onTouchStart, this, true);
        this.node.on("touchmove", this.onTouchMove, this, true);
        this.node.on("touchend", this.onTouchEnd, this, true);
        this.node.on("touchcancel", this.onTouchCancel, this, true);
    }

    public getDiretion():cc.Vec2 {

        return this._dir;
    }


    private onTouchStart(touch:cc.Event.EventTouch) {
        let location = touch.getLocation();
        location = this.node.convertToNodeSpaceAR(location);
        if (location.mag() >= this._radius) {
            location = location.normalizeSelf().mulSelf(this._radius);
        }
        this._dir = cc.pNormalize(location);
        this.jsPoint.setPosition(location);
    }

    private onTouchMove(touch:cc.Event.EventTouch) {
        let location = touch.getLocation();
        location = this.node.convertToNodeSpaceAR(location);
        if (location.mag() >= this._radius) {
            location = location.normalizeSelf().mulSelf(this._radius);
        }
        this._dir = cc.pNormalize(location);
        this.jsPoint.setPosition(location);
    }

    private onTouchEnd(touch:cc.Event.EventTouch) {
        this._dir = cc.v2(0, 0);
        this.jsPoint.setPosition(0, 0);
    }

    private onTouchCancel(event:cc.Event) {
        this._dir = cc.v2(0, 0);
        this.jsPoint.setPosition(0, 0);
    }
}
